package com.itheima.spring.spring;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author ：sean
 * @date ：Created in 2020/6/28
 * @description ：
 * @version: 1.0
 */
@Component
public class HeimaBeanPostProcessor implements BeanPostProcessor {
	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		if("userServiceImpl".equals(beanName)){
			System.out.println("userServiceImpl BeanPostProcessor postProcessBeforeInitialization...");
		}
		return bean;
	}

	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		if("userServiceImpl".equals(beanName)){
			System.out.println("userServiceImpl BeanPostProcessor postProcessAfterInitialization...");
		}
		if( bean != null && bean.getClass().getName().contains("UserService")){
			//System.out.println("BeanPostProcessor postProcessAfterInitialization...");
			//使用动态代理偷偷修改原本的实现类逻辑
			//Object o = Proxy.newProxyInstance(this.getClass().getClassLoader(),
			//		bean.getClass().getInterfaces(),
			//		new InvocationHandler() {
			//			@Override
			//			public Object invoke(Object proxy, Method method, Object[] args) throws
			//					Throwable {
			//				if(method.getName().contains("toString")){
			//					// 如果是toString方法，打印代理对象的信息
			//					return proxy.getClass().getName()+"@"+proxy.hashCode();
			//				}
			//				long start = System.currentTimeMillis();
			//				Object result = method.invoke(bean, args);
			//				long end = System.currentTimeMillis();
			//				System.out.println("正在执行:"+method.getName()+"方法---花费了:"+(end-start)+"毫秒");
			//				return result;
			//			}
			//		});
			//return o;
		}
		return bean;
	}

}
